package fr.afcepf.vod.dao;

import java.util.List;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import fr.afcepf.vod.entities.Description;
import fr.afcepf.vod.entities.Tag;
import fr.afcepf.vod.entities.Video;
@Named
@Transactional
public class DaoTagImpl implements IDaoTag {
	@PersistenceContext
	private EntityManager em;
	
	@Override
	public int getMaxOccurences() {
		Query query = em.createQuery("select max(tag.nbOccurencesRecherche) from Tag tag");
		return (Integer)query.getSingleResult();
	}

	@Override
	public List<Tag> getListeTags() {
		Query query = em.createQuery("from Tag tag");
		return query.getResultList();
	}

	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	@Override
	public List<Video> getVideosByTagMessage(String message) {
		Query query = em.createQuery("from Video v inner join fetch v.descriptions d where d.intitule = :message");
		query.setParameter("message", message);
		return query.getResultList();
	}

	@Override
	public void associerTagDescription(Description d) {
		Description descriptionBase = (Description) em.find(Description.class, d.getIdDescription());
		Tag tag = new Tag();
		em.persist(tag);
		descriptionBase.setTag(tag);
		tag.setDescription(descriptionBase);
		em.merge(descriptionBase);
		em.merge(tag);
	}

	@Override
	public Tag getTagByMessage(String message) {
		Query query = em.createQuery("from Tag tag inner join fetch tag.description d where d.intitule = :message");
		query.setParameter("message", message);
		List<Tag> listeResultat = (List<Tag>)query.getResultList();
		if(listeResultat.size() != 1){
			return null;
		}
		return listeResultat.get(0);
	}

	@Override
	public void updateTag(Tag tag) {
		em.merge(tag);
		
	}

}
